package com.pet.web.controller.system;

import com.pet.common.annotation.Log;
import com.pet.common.constant.UserConstants;
import com.pet.common.core.controller.BaseController;
import com.pet.common.core.domain.AjaxResult;
import com.pet.common.core.domain.entity.SysDept;
import com.pet.common.core.domain.entity.SysRole;
import com.pet.common.core.domain.entity.SysUser;
import com.pet.common.core.domain.model.LoginUser;
import com.pet.common.core.page.TableDataInfo;
import com.pet.common.enums.BusinessType;
import com.pet.common.utils.SecurityUtils;
import com.pet.common.utils.StringUtils;
import com.pet.common.utils.poi.ExcelUtil;
import com.pet.framework.web.service.TokenService;
import com.pet.system.service.ISysDeptService;
import com.pet.system.service.ISysPostService;
import com.pet.system.service.ISysRoleService;
import com.pet.system.service.ISysUserService;
import com.pet.web.controller.system.vo.UserBody;
import com.pet.web.controller.system.vo.UserPwdBody;
import com.pet.web.controller.system.vo.UserResultBody;
import com.pet.web.controller.system.vo.UserUpdateBody;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户信息
 *
 * @author pet
 */
@Api(value = "商户信息", tags = "商户管理")
@RestController
@RequestMapping("/system/user")
public class SysUserController extends BaseController {
    @Autowired
    private ISysUserService userService;

    @Autowired
    private TokenService tokenService;

    /**
     * 根据用户编号获取详细信息
     */
    @ApiOperation("根据用户编号获取详细信息")
    @PreAuthorize("@ss.hasPermi('system:user:query')")
    @GetMapping(value = {"/{userId}"})
    public AjaxResult getInfo(@PathVariable(value = "userId") Long userId) {
        if (!userId.equals(getUserId())) {
            return AjaxResult.error("登录用户只能查询本人的信息");
        }
        SysUser sysUser = userService.selectUserById(userId);
        UserResultBody userResultBody = new UserResultBody();
        BeanUtils.copyProperties(sysUser, userResultBody);
        return AjaxResult.success().put(AjaxResult.DATA_TAG, userResultBody);
    }

    /**
     * 新增用户
     */
    @ApiOperation("新增用户")
    @ApiImplicitParam(name = "userBody", value = "userBody", required = true, dataTypeClass = UserBody.class)
    @PreAuthorize("@ss.hasPermi('system:user:add')")
    @PostMapping
    public AjaxResult add(@Validated @RequestBody UserBody userBody) {
        SysUser user = new SysUser();
        user.setMerchantCode(getMerchantCode());
        user.setMerchantName(userBody.getMerchantName());
        user.setMerchantTips(userBody.getMerchantTips());
        user.setAddress(userBody.getAddress());
        user.setWechat(userBody.getWechat());
        user.setMobile(userBody.getMobile());
        user.setContactMobile(userBody.getContactMobile());
        user.setPassword(userBody.getPassword());
        user.setDeptId(1L);
        SysDept sysDept = new SysDept();
        sysDept.setDeptId(1L);
        user.setDept(sysDept);
        Long[] postIds = {1L};
        user.setPostIds(postIds);

        Long[] roleIds = {2L};
        user.setRoleIds(roleIds);
        user.setRoleId(2L);
        if (StringUtils.isNotEmpty(user.getMobile())
                && UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
            return AjaxResult.error("新增用户'" + userBody.getMobile() + "'失败，登录手机号码已存在");
        }
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        return toAjax(userService.insertUser(user));
    }

    private String getMerchantCode() {
        String code = genCode();
        SysUser sysUser = userService.checkMerchantCodeUnique(code);
        if (ObjectUtils.isEmpty(sysUser)) {
            //代表没有重复
            return code;
        }
        return getMerchantCode();
    }

    private static String genCode() {
        char c = 'A';
        c = (char) (c + (int) (Math.random() * 26));
        int cc = (int) ((Math.random() * 9 + 1) * 100000);
        return c + String.valueOf(cc);
    }

    /**
     * 修改用户
     */
    @ApiOperation(value = "修改用户")
    @ApiImplicitParam(name = "userUpdateBody", value = "userUpdateBody", required = true, dataTypeClass = UserUpdateBody.class)
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody UserUpdateBody userUpdateBody) {
        if (!userUpdateBody.getUserId().equals(getUserId())) {
            return AjaxResult.error("登录用户只能修改本人的信息");
        }
        SysUser user = new SysUser();
        user.setUserId(userUpdateBody.getUserId());
        user.setMerchantName(userUpdateBody.getMerchantName());
        user.setMerchantTips(userUpdateBody.getMerchantTips());
        user.setAddress(userUpdateBody.getAddress());
        user.setWechat(userUpdateBody.getWechat());
        user.setContactMobile(userUpdateBody.getContactMobile() );
        return toAjax(userService.updateUser(user));
    }

    /**
     * 重置密码
     */
    @ApiOperation("重置密码")
    @ApiImplicitParam(name = "userPwdBody", value = "userPwdBody", dataTypeClass = UserPwdBody.class)
    @PreAuthorize("@ss.hasPermi('system:user:resetPwd')")
    @PostMapping("/resetPwd")
    public AjaxResult resetPwd(@RequestBody UserPwdBody userPwdBody) {
        LoginUser loginUser = getLoginUser();
        String mobile = loginUser.getUser().getMobile();
        String password = loginUser.getPassword();
        if (!SecurityUtils.matchesPassword(userPwdBody.getOldPassword(), password)) {
            return AjaxResult.error("修改密码失败，旧密码错误");
        }
        if (SecurityUtils.matchesPassword(userPwdBody.getNewPassword(), password)) {
            return AjaxResult.error("新密码不能与旧密码相同");
        }
        if (userService.resetUserPwd(mobile, SecurityUtils.encryptPassword(userPwdBody.getNewPassword())) > 0) {
            // 更新缓存用户密码
            loginUser.getUser().setPassword(SecurityUtils.encryptPassword(userPwdBody.getNewPassword()));
            tokenService.setLoginUser(loginUser);
            return AjaxResult.success();
        }
        return AjaxResult.error("修改密码异常，请联系管理员");
    }
}
